<!DOCTYPE html>
<html>
    <head>
        <meta charset = "UTF-8">
        <title>cookie</title>
        <script>
            //去左空格;
            function ltrim(s){
                return s.replace(/(^\s*)/, "");
            }
            //去右空格;
            function rtrim(s){
                return s.replace(/(\s*$)/, "");
            }
            //去左右空格;
            function trim(s){
                //s.replace(/(^\s*)|(\s*$)/, "");
                return rtrim(ltrim(s));

            }

            //读取cookie
            var getCookie = function(key) {
                var cookie = document.cookie;
                var arr = cookie.split(';');
                for (var i = 0; i < arr.length; i++) {
                    var re = arr[i].split('=');
                    if (key == trim(re[0])) {
                        return re[1];
                    }
                }
            };

            //设置cookie
            var setCookie = function(key, value, time) {
                var _t = '';
                if (time) {
                    var d = new Date();
                    d.setSeconds(d.getSeconds() + time);
                    _t = ';expires=' + d.toGMTString();
                }
                document.cookie = key + '=' + value + _t;
            };

            //数组操作的各种方法
            window.onload = function() {
                //访问cookie,看是否有账号和密码
                console.info(document.cookie);

                //如果有账号和密码则提交表单
                var _name = getCookie('name');
                var _pass = getCookie('pass');
                if (_name && _pass) {
                    document.getElementById('txt_name').value = _name;
                    document.getElementById('txt_pass').value = _pass;
                    //document.getElementById('theForm').submit();
                }

                //提交按钮的事件
                document.getElementById('btnSub').onclick = function() {
                    //判断是否钩上 记住密码
                    if (document.getElementById('chkKeep').checked) {
                        setCookie('name', document.getElementById('txt_name').value, 10);
                        setCookie('pass', document.getElementById('txt_pass').value, 10);
                    }
                    document.getElementById('theForm').submit();
                };
            };
        </script>
    </head>

    <body>
        <form id = 'theForm' action = '' method = 'post'>
            用户名:<input id = 'txt_name' type = 'text' /><br/>
            密码:<input id = 'txt_pass' type = 'password' /><br/>
            <input id = 'chkKeep' type = 'checkbox' />记住账号密码<br/>
            <button id = 'btnSub' type = 'button'>提交</button>
        </form>
    </body>
</html>